﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Icst.Leaflike.Web;

using Icst.Leaflike.Web.controls;
using System.Web.UI.HtmlControls;
using Icst.Leaflike.Data;
using System.IO;
using System.Drawing;
using Icst.Leaflike.SAFG;
using System.Text;

namespace Icst.Leaflike.Web.search
{
    public partial class leaf : pagesearch
    {
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            AddSelection(yejianSelector, Tree.YEJIAN);
            AddSelection(yejiSelector, Tree.YEJI);
            AddSelection(yeyuanSelector, Tree.YEYUAN);
            AddSelection(yexingSelector, Tree.YEXING);
        }

        protected void treeUploader_UploadedFileError(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
        {
        }

        protected void saveButton_Click(object sender, EventArgs e)
        {
            treeUploader_UploadedComplete(sender, null);
        }

        protected void treeUploader_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
        {
            string[] acceptedExt = new string[]{"jpg","jpeg","gif"};
            Searcher worker = new Searcher();
            if (treeUploader.HasFile && acceptedExt.Any(p=>treeUploader.FileName.ToLower().Contains(p)))
            {
                //tree_attr[] attrs = worker.SearchYeXing(postedFile.InputStream, postedFile.ContentType, postedFile.FileName, Session.UserData().Version);
                //yexingSelector.DisplayItemsOnly(attrs.Select(p => p.attr_no).ToArray());
                string safefilename = treeUploader.FileName;
                Path.GetInvalidFileNameChars().ToList().ForEach(p => safefilename = safefilename.Replace(p.ToString(), ""));

                string fileName = "u_" + DateTime.Now.ToString("yyyyMMddhh") + "_" + safefilename;
                string uploadPath = Path.Combine(Server.MapPath("~/contours"), fileName);
                try
                {
                    treeUploader.SaveAs(uploadPath);
                }
                catch { }

                //
                Contour[] contours = GenerateContour(uploadPath);
                Dictionary<string, string> countourImages = GenerateContourImages(contours);

                AddSelection(yeziselector, countourImages);
                if (countourImages.Count > 0)
                    yeziValue.Value = yeziselector.Selected;

                Switch(true);
            }
        }

        private Dictionary<string, string> GenerateContourImages(Contour[] contours)
        {
            Dictionary<string, string> images = new Dictionary<string, string>();
            Dictionary<string, Contour> contourWithKeys = new Dictionary<string, Contour>();

            string basepath = Server.MapPath("~/contours");
            foreach (var contour in contours)
            {
                string key = Guid.NewGuid().ToString();
                string image = key + ".jpg";
                using (Bitmap b = ImageExtension.Contour(640, 480, contour.Points.Select(p => new Point(p.X, p.Y)).ToList()))
                {
                    b.Save(Path.Combine(basepath,image));
                }
                images[key] = "contours/" + image;

                //string contourFile = Path.Combine(basepath, key + ".cont");
                //StringBuilder sb = new StringBuilder();
                //foreach (var p in contour.Points) 
                //{
                //    sb.AppendLine(string.Format("{0},{1}", p.X, p.Y)); 
                //}
                //File.WriteAllText(contourFile,sb.ToString());
                contourWithKeys[key] = contour;
            }
            Session["contours"] = contourWithKeys;

            return images;
        }

        private Contour[] GenerateContour(string uploadPath)
        {
            //byte[] bytes = File.ReadAllBytes(uploadPath);
            //using (SAFGClient c = new SAFGClient())
            //{
            //    return c.SearchContours(bytes);
            //}

            using (SAFGClient c = new SAFGClient())
            {
                return c.SearchContoursByPath(uploadPath);
            }
        }

        protected override string OnSave(bool empty)
        {
            string fileName = "u_" + DateTime.Now.ToString("yyyyMMddhh") + "_" + treeUploader.FileName;

            SearchQuery[SearchOption.Yejian] = empty ? string.Empty : yejianSelector.Selected;
            SearchQuery[SearchOption.Yeji] = empty ? string.Empty : yejiSelector.Selected;
            SearchQuery[SearchOption.Yeyuan] = empty ? string.Empty : yeyuanSelector.Selected;
            SearchQuery[SearchOption.Yeji] = empty ? string.Empty : yeyuanSelector.Selected;
            SearchQuery[SearchOption.isUpload] = empty ? "False" : uploadLink.Checked.ToString();
            SearchQuery[SearchOption.Yexing] = empty ? string.Empty : (uploadLink.Checked ? yeziValue.Value : yexingSelector.Selected);
            return "search_flower.htm";
        }
        protected override void OnLoad()
        {
            yejianSelector[SearchQuery[SearchOption.Yejian]] = true;
            yejiSelector[SearchQuery[SearchOption.Yeji]] = true;
            yeyuanSelector[SearchQuery[SearchOption.Yeyuan]] = true;
            yexingSelector[SearchQuery[SearchOption.Yexing]] = true;

            if (SearchQuery.IsUpload)
            {
                SearchQuery[SearchOption.isUpload] = "False";
                SearchQuery[SearchOption.Yexing] = string.Empty;
            }
            Switch(SearchQuery.IsUpload);
        }

        private void Switch(bool isupload)
        {
            uploadDiv.Style[HtmlTextWriterStyle.Display] = isupload ? "block" : "none";
            selectDiv.Style[HtmlTextWriterStyle.Display] = !isupload ? "block" : "none";
            selectLink.Checked = !isupload;
            uploadLink.Checked = isupload;
        }
    }
}
